<template>
  <view class="Mall4j component-imgs-upload">
    <!-- 多图 -->
    <view
      class="upload"
      :style="{justifyContent: uploadPosition}"
    >
      <!-- 图片列表 -->
      <view
        v-for="(item, index) in imgFiles"
        :key="index"
        class="preview"
        :style="sty"
      >
        <image
          v-if="imgFiles.length > 0 && imgFiles.length <= imgNum"
          :src="item.url"
          mode="aspectFill"
          :data-index="index"
          @tap="getUploadImg"
        />
        <view
          class="del"
          @tap="removeImage(index)"
        >
          <image src="/static/images/close2.png" />
        </view>
        <view
          class="preview-img"
          @tap="onPreviewImage(index)"
        >
          预览
        </view>
      </view>
      <!-- 上传按钮 -->
      <view
        v-if="imgFiles.length < imgNum"
        class="upload-chequer"
        :style="sty"
        @tap="getUploadImg"
      >
        <view class="cross">
          ＋
        </view>
      </view>
    </view>
    <view
      v-if="prompt"
      class="tips"
    >
      最多可上传{{ imgNum }}张凭证
    </view>
    <helang-compress ref="hCompressRef" />
  </view>
</template>

<script setup>
import { computed } from 'vue'
import util from '@/utils/util'

const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  imgNum: { // 图片上传数量，默认1，最大9
    type: Number,
    default: 1
  },
  prompt: {
    type: Boolean,
    default: true
  },
  sty: {
    type: Object,
    default: () => ({})
  },
  uploadPos: {
    type: String,
    default: ''
  }
})

const uploadPosition = computed(() => {
  switch (props.uploadPos) {
    case 'left':
      return 'flex-start'
    case 'right':
      return 'flex-end'
    default:
      return 'flex-start'
  }
})

const imgFiles = ref([])
watch(() => props.modelValue, (val) => {
  imgFiles.value = onHandleImgs(val)
})
// 图片处理
const onHandleImgs = (imgStr) => {
  if (imgStr) {
    return imgStr.split(',').map(item => {
      return {
        path: item,
        url: util.checkFileUrl(item)
      }
    })
  }
  return []
}

onUnmounted(() => {
  if (isShowPreview) {
    uni.closePreviewImage({
      success: () => {
        isShowPreview = false
      }
    })
  }
})
/**
 * 上传图片
 */
const hCompressRef = ref(null)
let imgIndex = null // 当前点击的图片下标
const getUploadImg = (e) => {
  imgIndex = e.currentTarget.dataset.index
  const count = props.imgNum - imgFiles.value.length + (imgIndex ? 1 : 0)
  util.chooseImage({ compress: hCompressRef.value?.compress, count }).then(data => {
    data.forEach((item, index) => {
      if (imgIndex && index === 0) {
        imgFiles.value[imgIndex] = {
          path: item.filePath,
          url: util.checkFileUrl(item.filePath)
        }
      } else {
        imgFiles.value.push({
          path: item.filePath,
          url: util.checkFileUrl(item.filePath)
        })
      }
    })
    onHandleEmit()
  })
}

const onHandleEmit = () => {
  const urls = imgFiles.value.reduce((acc, curr, inx) => {
    if (inx !== 0) {
      acc += ','
    }
    return acc + curr.path
  }, '')
  emit('update:modelValue', urls)
}

// 图片预览
let isShowPreview = false
const onPreviewImage = (current) => {
  const preViewList = imgFiles.value.map(item => item.url)
  uni.previewImage({
    current,
    urls: preViewList,
    success: () => {
      isShowPreview = true
    }
  })
}

/**
 * 删除图片
 */

const removeImage = (idx) => {
  imgFiles.value.splice(idx, 1)
  onHandleEmit()
}
</script>

<style lang="scss" scoped>
.component-imgs-upload {
    display: block;
    .upload {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      width: 100%;
      height: 100%;
      background: #fff;
      row-gap: 20rpx;
      .preview {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        background: #f9f9f9;
        position: relative;
        margin-right: 20rpx;
        image {
          display: block;
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }
        .del {
          position: absolute;
          top: 0;
          right: 0;
          width: 36rpx;
          height: 36rpx;
          font-size: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(0,0,0,.3);
          border-radius: 0 8rpx 0 30rpx;
          image {
            width: 14rpx;
            height: 14rpx;
            margin: 0 0 2rpx 2rpx;
          }
        }
        .preview-img {
          position: absolute;
          bottom: 0;
          display: block;
          width: 100%;
          height: 2em;
          line-height: 2em;
          background: rgba(0,0,0,.3);
          text-align: center;
          color: #fff;
          border-radius: 0 0 8rpx 8rpx;
          font-size: 24rpx;
        }
      }
      .upload-chequer {
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        background: #F6F8FA;
        display: flex;
        align-items: center;
        justify-content: center;
        .cross {
          font-size: 96rpx;
          font-weight: 200;
          color: #ccc;
        }
      }
    }
    .tips{
      font-size: 24rpx;
      color: #666;
      margin-top: 16rpx;
    }
  }
</style>
